package com.example.administrator.fastdream.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.administrator.fastdream.R;
import com.example.administrator.fastdream.date.bean.BaseBean;
import com.example.administrator.fastdream.date.bean.ChooseMoneyBean;
import com.example.administrator.fastdream.date.bean.LookDreamBean;
import com.example.administrator.fastdream.date.bean.UploadPhotoBean;
import com.example.administrator.fastdream.date.presenter.DreamPresenter;
import com.example.administrator.fastdream.date.utils.CacheUtils;
import com.example.administrator.fastdream.date.utils.DimenUtil;
import com.example.administrator.fastdream.date.utils.MyUtils;
import com.example.administrator.fastdream.date.utils.PhotoHelper;
import com.example.administrator.fastdream.view.base.BaseActivity;
import com.example.administrator.fastdream.view.base.BaseDialog;
import com.example.administrator.fastdream.view.view.NoScrollViewPager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyDreamActivity extends BaseActivity implements DreamPresenter.DreamCallBack {

    @BindView(R.id.iv_mine)
    ImageView ivMine;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.viewpager)
    NoScrollViewPager viewpager;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_xuanyan)
    TextView tvXuanyan;
    @BindView(R.id.tv_smaple)
    TextView tvSmaple;
    @BindView(R.id.tv_count)
    TextView tv_count;
    @BindView(R.id.recycler_photo)
    RecyclerView recyclerPhoto;
    @BindView(R.id.tv_save)
    TextView tvSave;
    private BaseDialog mDialog;
    private BaseDialog.Builder mBuilder;
    private List<String> photoList = new ArrayList<>();
    private List<File> fileList = new ArrayList<>();
    private List<Integer> photoSmapleList = new ArrayList<>();
    private PhotoAdapter photoAdapter;
    private int maxCount = 9;
    private int status;
    private DreamPresenter presenter;
    private String dream_name, dream_money;
    private List<String> nameList = new ArrayList<>();
    private List<String> desList = new ArrayList<>();
    private int vpCurrentPosition;
    private boolean isEdit;
    private List<String> previousPhotoList = new ArrayList<>();
    private LookDreamBean.DataEntity.DreamInfoEntity dream_info;
    private boolean isPreviousDeleted;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_dream);
        ButterKnife.bind(this);
        ivBack.setVisibility(View.VISIBLE);
        tvTitle.setText("我的梦想");
        recyclerPhoto.setNestedScrollingEnabled(false);
        recyclerPhoto.setLayoutManager(new GridLayoutManager(this, 3));
        initData();
        presenter = new DreamPresenter(this, this);
        presenter.lookDream();
    }

    private void refreshStatus() {
        if (status == 1) {//已经保存过梦想
            isEdit = false;
            viewpager.setCanScroll(false);
            tvSave.setText("分享梦想");
            tvRight.setVisibility(View.VISIBLE);
            tvRight.setText("修改");
            tvMoney.setClickable(false);
            tvXuanyan.setClickable(false);
            tvSmaple.setVisibility(View.GONE);
            tv_count.setVisibility(View.VISIBLE);
        } else {//没保存过梦想
            isEdit = true;
            dream_name = (String) CacheUtils.get("dream_name");
            dream_money = (String) CacheUtils.get("dream_money");
            vpCurrentPosition = getVpCurrentPosition(dream_name);
            viewpager.setAdapter(new DreamAdapter());
            viewpager.setCurrentItem(vpCurrentPosition);
            tvXuanyan.setText(desList.get(vpCurrentPosition));
            tvMoney.setText(dream_money);
            refreshRecycler();
        }
    }

    private void refreshRecycler() {
        if (photoList.size() == 0) {
            photoList.add("");
        } else if (photoList.size() != maxCount && !photoList.get(photoList.size() - 1).equals("")) {
            photoList.add("");
        }
        photoAdapter = new PhotoAdapter(R.layout.item_photo, photoList);
        recyclerPhoto.setAdapter(photoAdapter);
        photoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (photoList.get(photoList.size() - 1).equals("") && isEdit) {
                    PhotoHelper.choosePhoto(MyDreamActivity.this, maxCount - photoList.size() + 1,
                            DimenUtil.dp2px(mContext, 106), DimenUtil.dp2px(mContext, 106));
                }
            }
        });
        photoAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.iv_del && isEdit) {
                    if (status == 1 && photoList.get(position).contains("http")) {
                        isPreviousDeleted = true;
                        previousPhotoList.remove(position);
                    }
                    photoList.remove(position);
                    if (photoList.size() != maxCount && !photoList.get(photoList.size() - 1).equals("")) {
                        photoList.add("");
                    }
                    photoAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    public void saveDream(BaseBean baseBean) {
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        CacheUtils.remove("dream_name");
        CacheUtils.remove("dream_money");
        tvSave.setText("分享梦想");
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("修改");
        tvMoney.setClickable(false);
        tvXuanyan.setClickable(false);
        tvSmaple.setVisibility(View.GONE);
        tv_count.setVisibility(View.VISIBLE);
        isEdit = false;
        photoList.clear();
        previousPhotoList.clear();
        presenter.lookDream();
    }

    @Override
    public void uploadPhotos(UploadPhotoBean uploadPhotoBean) {
        String images = uploadPhotoBean.getData().getImg();
        if (status == 0) {//上传完了图片之后就保存梦想
            presenter.saveDream(dream_name, dream_money, desList.get(vpCurrentPosition), images);
        } else {//编辑之前保存过的梦想
            StringBuilder stringBuilder = new StringBuilder();
            if (previousPhotoList.size() > 0) {
                for (int i = 0; i < previousPhotoList.size(); i++) {
                    stringBuilder.append(previousPhotoList.get(i) + ",");
                }
            }
            if (stringBuilder.toString().length() > 0) {
                presenter.editDream(dream_name, dream_money, desList.get(vpCurrentPosition), stringBuilder.toString() + images);
            } else {
                //把之前上传的图片全删了，然后添加的新的图片
                presenter.editDream(dream_name, dream_money, desList.get(vpCurrentPosition), images);
            }
        }
    }

    @Override
    public void lookDream(LookDreamBean lookDreamBean) {
        if (lookDreamBean.getData().getDream_info() == null) {
            status = 0;
            refreshStatus();
            return;
        } else {
            status = 1;
            refreshStatus();
        }
        dream_info = lookDreamBean.getData().getDream_info();
        dream_name = dream_info.getDream_name();
        dream_money = dream_info.getDream_money();
        vpCurrentPosition = getVpCurrentPosition(dream_name);
        viewpager.setAdapter(new DreamAdapter());
        viewpager.setCurrentItem(vpCurrentPosition);
        tvMoney.setText(dream_money + "万");
        tvXuanyan.setText(dream_info.getDream_declaration());
        List<LookDreamBean.DataEntity.DreamInfoEntity.ImagesEntity> images = dream_info.getImages();
        if (images != null && images.size() > 0) {
            for (int i = 0; i < images.size(); i++) {
                photoList.add(images.get(i).getImg_url());
            }
        }
        tv_count.setText(photoList.size() + "张");
        refreshRecycler();
        //之前上传过的图片保存在集合里
        for (int i = 0; i < photoList.size(); i++) {
            if (photoList.get(i).contains("http")) {
                String[] uploads = photoList.get(i).split("Uploads");
                previousPhotoList.add("/Uploads" + uploads[1]);
            }
        }
    }

    private class PhotoAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        public PhotoAdapter(int layoutResId, @Nullable List<String> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            ImageView iv_photo = helper.getView(R.id.iv_photo);
            ImageView iv_del = helper.getView(R.id.iv_del);
            helper.addOnClickListener(R.id.iv_del);
            if (item.equals("") && isEdit) {
                Glide.with(mContext).load(R.drawable.upload_photo).into(iv_photo);
                iv_del.setVisibility(View.GONE);
            } else {
                iv_del.setVisibility(isEdit ? View.VISIBLE : View.GONE);
                Glide.with(mContext).load(item).into(iv_photo);
            }
        }
    }

    private class PhotoSampleAdapter extends BaseQuickAdapter<Integer, BaseViewHolder> {

        public PhotoSampleAdapter(int layoutResId, @Nullable List<Integer> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, Integer item) {
            ImageView iv_photo = helper.getView(R.id.iv_photo);
            iv_photo.setImageResource(item);
        }
    }

    private class MoneyAdapter extends BaseQuickAdapter<ChooseMoneyBean, BaseViewHolder> {

        public MoneyAdapter(int layoutResId, @Nullable ArrayList<ChooseMoneyBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(final BaseViewHolder helper, ChooseMoneyBean item) {
            ImageView iv_img = helper.getView(R.id.iv_img);
            iv_img.setImageResource(item.getImage());
            helper.setText(R.id.tv_content, item.getContent());
            ImageView iv_check = helper.getView(R.id.iv_check);
            if (item.isChecked()) {
                iv_check.setImageResource(R.drawable.checked);
            } else {
                iv_check.setImageResource(R.drawable.unchecked);
            }
            helper.addOnClickListener(R.id.iv_check);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // sample1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    for (int i = 0; i < selectList.size(); i++) {
                        photoList.add(photoList.size() - 1, selectList.get(i).getCompressPath());
                    }
                    if (photoList.get(photoList.size() - 1).equals("")) {
                        photoList.remove(photoList.size() - 1);
                    }
                    refreshRecycler();
                    fileList = new ArrayList<>();
                    if (photoList.size() == 9) {
                        for (int i = 0; i < photoList.size(); i++) {
                            if (!photoList.get(i).contains("http")) {//说明不是之前上传过的图片
                                fileList.add(new File(photoList.get(i)));
                            }
                        }
                    } else {
                        //别忘了图片不足9张的时候还会有个拍照图
                        for (int i = 0; i < photoList.size() - 1; i++) {
                            if (!photoList.get(i).contains("http")) {//说明不是之前上传过的图片
                                fileList.add(new File(photoList.get(i)));
                            }
                        }
                    }
                    break;
            }
        }
    }

    private class DreamAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return 4;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            //            return super.instantiateItem(container, position);
            View view = View.inflate(mContext, R.layout.item_vp, null);
            ImageView iv_root = view.findViewById(R.id.iv_root);
            TextView tv_content = view.findViewById(R.id.tv_content);
            switch (position) {
                case 0:
                    iv_root.setImageResource(R.drawable.vp1);
                    tv_content.setText(nameList.get(0));
                    break;
                case 1:
                    iv_root.setImageResource(R.drawable.vp2);
                    tv_content.setText(nameList.get(1));
                    break;
                case 2:
                    iv_root.setImageResource(R.drawable.vp3);
                    tv_content.setText(nameList.get(2));
                    break;
                case 3:
                    iv_root.setImageResource(R.drawable.vp4);
                    tv_content.setText(nameList.get(3));
                    break;
            }
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            //            super.destroyItem(container, position, object);
            container.removeView((View) object);
        }
    }

    private void showPhotoSampleDialog() {
        mBuilder = new BaseDialog.Builder(this);
        mDialog = mBuilder.setViewId(R.layout.dialog_photo_sample)
                //设置dialogpadding
                .setPaddingdp(10, 0, 10, 0)
                //设置显示位置
                .setGravity(Gravity.CENTER)
                //设置动画
                .setAnimation(R.style.Alpah_aniamtion)
                //设置dialog的宽高
                .setWidthHeightpx(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                //设置触摸dialog外围是否关闭
                .isOnTouchCanceled(true)
                //设置监听事件
                .builder();
        mDialog.show();
        RecyclerView recycler_photo_sample = mDialog.getView(R.id.recycler_photo_sample);
        recycler_photo_sample.setLayoutManager(new GridLayoutManager(mContext, 3));
        PhotoSampleAdapter photoSampleAdapter = new PhotoSampleAdapter(R.layout.item_photo, photoSmapleList);
        recycler_photo_sample.setAdapter(photoSampleAdapter);
    }

    private void showModifyDesDialog(final TextView tvmodel, String title, String content) {
        mBuilder = new BaseDialog.Builder(this);
        int dialog_width = MyUtils.getScreenWidth(this) - DimenUtil.dp2px(this, 40);
        int dialog_height = (int) (dialog_width / 2f);
        mDialog = mBuilder.setViewId(R.layout.dialog_modify_info)
                //设置dialogpadding
                .setPaddingdp(20, 0, 20, 0)
                //设置显示位置
                .setGravity(Gravity.CENTER)
                //设置动画
                .setAnimation(R.style.Alpah_aniamtion)
                //设置dialog的宽高
                .setWidthHeightpx(LinearLayout.LayoutParams.MATCH_PARENT, dialog_height)
                //设置触摸dialog外围是否关闭
                .isOnTouchCanceled(true)
                //设置监听事件
                .builder();
        mDialog.show();
        TextView tv_title = mDialog.getView(R.id.tv_title);
        final EditText et_content = mDialog.getView(R.id.et_content);
        tv_title.setText(title);
        et_content.setText(content);
        mDialog.getView(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDialog.getView(R.id.tv_yes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvmodel.setText(et_content.getText().toString());
                desList.set(vpCurrentPosition, et_content.getText().toString());
                mDialog.dismiss();
            }
        });
    }

    private void showModifyMoneyDialog(final TextView tvmodel, String title, String content) {
        mBuilder = new BaseDialog.Builder(this);
        mDialog = mBuilder.setViewId(R.layout.dialog_modify_money)
                //设置dialogpadding
                .setPaddingdp(20, 0, 20, 0)
                //设置显示位置
                .setGravity(Gravity.CENTER)
                //设置动画
                .setAnimation(R.style.Alpah_aniamtion)
                //设置dialog的宽高
                .setWidthHeightpx(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                //设置触摸dialog外围是否关闭
                .isOnTouchCanceled(true)
                //设置监听事件
                .builder();
        mDialog.show();
        RecyclerView recyclerView = mDialog.getView(R.id.recyclerView);
        final TextView tv_yes = mDialog.getView(R.id.tv_yes);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        recyclerView.setNestedScrollingEnabled(false);
        final ArrayList<ChooseMoneyBean> list = new ArrayList<>();
        list.add(new ChooseMoneyBean(R.drawable.yiwan, "1万元", ""));
        list.add(new ChooseMoneyBean(R.drawable.wuwan, "5万元", ""));
        list.add(new ChooseMoneyBean(R.drawable.shiwuwan, "15万元", ""));
        list.add(new ChooseMoneyBean(R.drawable.ershiwan, "20万元", ""));
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getContent().contains(content)) {
                list.get(i).setChecked(true);
            }
        }
        final MoneyAdapter moneyAdapter = new MoneyAdapter(R.layout.item_choose_dream, list);
        recyclerView.setAdapter(moneyAdapter);
        moneyAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < list.size(); i++) {
                    if (i == position) {
                        list.get(position).setChecked(!list.get(position).isChecked());
                    } else {
                        list.get(i).setChecked(false);//注意这里是i
                    }
                }
                moneyAdapter.notifyDataSetChanged();
                if (!isChooseDream(list)) {
                    tv_yes.setBackgroundResource(R.drawable.shape_button_unchecked);
                } else {
                    tv_yes.setBackgroundResource(R.drawable.shape_button_checked);
                }
            }
        });
        tv_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).isChecked()) {
                        dream_money = list.get(i).getContent();
                        tvmodel.setText(dream_money);
                    }
                }
                mDialog.dismiss();
            }
        });
    }

    private boolean isChooseDream(ArrayList<ChooseMoneyBean> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isChecked()) {
                return true;
            }
        }
        return false;
    }

    @OnClick({R.id.iv_back, R.id.tv_right, R.id.tv_money, R.id.tv_xuanyan, R.id.tv_smaple, R.id.tv_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_money:
                showModifyMoneyDialog(tvMoney, "选择所需资金", tvMoney.getText().toString());
                break;
            case R.id.tv_xuanyan:
                showModifyDesDialog(tvXuanyan, "修改梦想宣言", tvXuanyan.getText().toString());
                break;
            case R.id.tv_smaple:
                showPhotoSampleDialog();
                break;
            case R.id.tv_save:
                if (tvSave.getText().toString().equals("保存")) {
                    if (photoList.size() == 0 || photoList.get(0).equals("")) {
                        Toast.makeText(this, "请选择梦想图片", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (fileList.size() > 0) {
                        presenter.uploadPhotos(fileList);
                    } else {
                        if (dream_info != null && dream_info.getDream_declaration().equals(tvXuanyan.getText().toString())
                                && dream_money.equals(dream_info.getDream_money())
                                && dream_name.equals(dream_info.getDream_name())
                                && !isPreviousDeleted) {
                            Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                            tvSave.setText("分享梦想");
                            tvRight.setVisibility(View.VISIBLE);
                            tvRight.setText("修改");
                            tvMoney.setClickable(false);
                            tvXuanyan.setClickable(false);
                            tvSmaple.setVisibility(View.GONE);
                            tv_count.setVisibility(View.VISIBLE);
                            isEdit = false;
                            photoAdapter.notifyDataSetChanged();
                        } else {
                            StringBuilder stringBuilder = new StringBuilder();
                            if (previousPhotoList.size() > 0) {
                                for (int i = 0; i < previousPhotoList.size(); i++) {
                                    if (i == previousPhotoList.size() - 1) {
                                        stringBuilder.append(previousPhotoList.get(i));
                                    } else {
                                        stringBuilder.append(previousPhotoList.get(i) + ",");
                                    }
                                }
                            }
                            presenter.editDream(dream_name, dream_money, desList.get(vpCurrentPosition), stringBuilder.toString());
                        }
                    }
                } else {

                }
                break;
            case R.id.tv_right:
                isEdit = true;
                viewpager.setCanScroll(true);
                tvMoney.setClickable(true);
                tvXuanyan.setClickable(true);
                tvSmaple.setVisibility(View.VISIBLE);
                tv_count.setVisibility(View.GONE);
                tvSave.setText("保存");
                refreshRecycler();
                break;
        }
    }

    private int getVpCurrentPosition(String name) {
        for (int i = 0; i < nameList.size(); i++) {
            if (nameList.get(i).equals(name)) {
                return i;
            }
        }
        return 1;
    }

    private void initData() {
        nameList.add("家乡创业");
        nameList.add("开个小店");
        nameList.add("开个网店");
        nameList.add("自由职业");
        desList.add("希望有一天能回家乡创业");
        desList.add("希望有一天能开自己的小店");
        desList.add("希望有一天能开个网店");
        desList.add("希望有一天能自由职业");
        photoSmapleList.add(R.drawable.demo1);
        photoSmapleList.add(R.drawable.demo2);
        photoSmapleList.add(R.drawable.demo3);
        photoSmapleList.add(R.drawable.demo4);
        photoSmapleList.add(R.drawable.demo5);
        photoSmapleList.add(R.drawable.demo6);
        photoSmapleList.add(R.drawable.demo7);
        photoSmapleList.add(R.drawable.demo8);
        photoSmapleList.add(R.drawable.demo9);
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                vpCurrentPosition = position;
                tvXuanyan.setText(desList.get(vpCurrentPosition));
                dream_name = nameList.get(vpCurrentPosition);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

}
